import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QFileDialog, QApplication
from qfluentwidgets import PushButton
from config import CONFIG_JSON
from tools import JsonEditor
from pathlib import Path


class OpenFileButton(PushButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.jsonEdit = JsonEditor(CONFIG_JSON)
        self.openFile = self.jsonEdit.get('OpenFile')
        if self.openFile is None:
            self.openFile = ''

    def getExistingDirectory(self):
        file = QFileDialog.getExistingDirectory(self, '选择文件夹', self.openFile)
        self.jsonEdit.setItem('OpenFile', file)
        return file

    def getOpenFileName(self, *args, filter='所有文件(*.*);'):
        file = QFileDialog.getOpenFileName(self, '选择文件', self.openFile, filter)
        if file[0] != '':
            self.jsonEdit.setItem('OpenFile', str(Path(file[0]).resolve().parent))
        return file

    def getOpenFileNames(self, *args, filter='所有文件(*.*);'):
        file = QFileDialog.getOpenFileNames(self, '选择多个文件', self.openFile, filter)
        if len(file[0]) > 0:
            self.jsonEdit.setItem('OpenFile', str(Path(file[0][0]).resolve().parent))
        return file


if __name__ == '__main__':
    QApplication.setHighDpiScaleFactorRoundingPolicy(
        Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
    )
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    app = QApplication(sys.argv)
    win = OpenFileButton()
    win.show()
    sys.exit(app.exec_())
